<template>
  <div id="actCoupon">
    <dialogContent v-if="show" @close="closeDialog" @addCoupon="addCoupon"></dialogContent>
    <div class="addBtn">*添加卡券<el-button @click="show=!show">+</el-button></div>
    <el-table :data="selCouponData" style="width: 100%" class="couponTable">
        <el-table-column v-for="items in tableOptions" :key="items.value" :prop="items.value"   :label="items.label"  min-width="50"  ></el-table-column>
        <el-table-column                        label="操作"      min-width="50">
          <template scope="scope">
            <el-button @click.native.prevent="disabledRow(scope.row)" v-if="hasPublish(scope.row)" :disabled="hasDisabled(scope.row)" type="text" size="small" >禁用</el-button>
            <el-button @click.native.prevent="deleteRow(scope.$index,scope.row)" v-else type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    <stepBtn :nextBtn="next" :successBtn="success" :prevBtn="prev" :saveBtn="save" :btnShow="btnShow" ></stepBtn>
  </div>
</template>
<script>
import dialogContent from './dialogContent'
import {InvestCouponLIst, financialCouponLIst, anthoderCouponList} from './config'
import {postLog} from 'api/common/index.js'
import {activityDetail} from 'api/activity'
import stepBtn from '../stepButton'
export default {
  components: {
    dialogContent, stepBtn
  },
  props: ['edit'],
  data () {
    return {
      btnShow: {                                                                                         //控制按钮展示
        next: false,
        prev: true,
        save: false,
        success: false
      },
      nowIndex: '',
      nextTap: '',
      prevTap: '',
      show: false,
      tableOptions: [],
      selCouponData: []
    }
  },
  created () {
    if (!this.edit) {
      this.checkStep();
    } else {
      this.btnShow.save = true
      this.btnShow.prev = false
    }
    this.getActivityDetail()
    this.actType === '产品投资' ? this.tableOptions = InvestCouponLIst : this.actType === '理财师每满送券' ? this.tableOptions = financialCouponLIst : this.tableOptions = anthoderCouponList
  },
  computed: {
    actTypeInfo () {
      return JSON.parse(sessionStorage.getItem('addActivityType'))
    },
    actType () {
      return JSON.parse(sessionStorage.getItem('actType')).text
    },
    status () {
      return sessionStorage.getItem('actStatus')
    }
  },
  methods: {
    async getActivityDetail () {
      try {
        let back = await activityDetail(sessionStorage.getItem('activityId'))
        back = back.data
        if (back.resultCode === '200') {
          let arr = [...back.result.coupons]
          arr.forEach(element => {
            // 后端字段不统一
            element.cardid = element.cardId
            element.cardDesc = element.cardName
            element.actType = back.result.info.typeText
            element.conditionShow = element.rewardTypeWay
          });
          this.selCouponData = arr
        } else {
          this.$alert(back.msg)
        }
      } catch (err) {
        this.$alert('请求失败', '提示')
      }
    },
    //  禁用卡券
    disabledRow (row) {
      let save = true;
      this.selCouponData.forEach(element => {
        if (!element.activityCouponId) {
          save = false;
          return
        }
      });
      if (save === false) {
        this.$alert('请先保存添加的卡券', '提示');
        return
      }
      console.log(row);
      this.$confirm('你确定要禁用该卡券吗?', '提示', {
      }).then(() => {
        this.$http.put('/api-active/v1/api/activityCenter/activity/disableCoupon?activityId=' + JSON.parse(sessionStorage.getItem('activityId')) + '&activityCouponId=' + row.activityCouponId)
            .then((response) => {
              let data = response.body;
              if (data.resultCode === '200') {
                this.getActivityDetail()
                this.$message({
                  type: 'success',
                  message: '页面已刷新!'
                });
              }
            })
      })
    },
    deleteRow (index, row) {
      if (row.activityCouponId) {
        let params = {activityId: JSON.parse(sessionStorage.getItem('activityId')), activityCouponId: row.activityCouponId + ''};
        this.$confirm('你确定要移除该卡券吗', '提示', {
        }).then(() => {
          this.$http.put('/api-active/v1/api/activityCenter/activity/deleteCoupon', params)
              .then((response) => {
                let data = response.body;
                if (data.resultCode == '200') {
                  this.selCouponData.splice(index, 1);
                  this.$message({
                    type: 'success',
                    message: '页面已刷新!'
                  });
                  this.$emit('getData');
                }
              });
        }).catch(() => {
        });
      } else {
        this.selCouponData.splice(index, 1);
      }
    },
    //  置灰禁用按钮
    hasDisabled (row) {
      // 如果这个活动已经禁止就置灰
      if (row.enable === 'NO') {
        return true
      } else {
        return false
      }
    },
    //  根据发布显示禁止按钮,
    hasPublish (row) {
      //如果活动已经发布且这个卡券不是刚新增的就显示禁止按钮
      if (this.status === '1' && row.activityCouponId !== undefined) {
        return true;
      } else {
        return false;
      }
    },
    checkStep () {
      let stepArr = this.actTypeInfo.relatedSectionsArray;
      //现在处于第几步
      this.nowIndex = stepArr.indexOf('COUPON');
      //下一步
      let nextIndex = this.nowIndex + 1;
      let prevIndex = this.nowIndex - 1;
      // 如果这是最后一步了
      if (nextIndex === stepArr.length) {
        this.btnShow.success = true;
        this.prevTap = stepArr[prevIndex];
      } else {
        this.btnShow.next = true;
        this.nextTap = stepArr[nextIndex];
        this.prevTap = stepArr[prevIndex];
      }
    },
    addCoupon (parm) {
      this.closeDialog()
    //如果列表里面没有就直接添加
      if (this.selCouponData.length === 0) {
        this.selCouponData.push(parm)
        return
      }
    //去重
      let add = true
      if (this.actType === '产品投资') {
        // alert('123');
        this.selCouponData.forEach(element => {
          element.type = element.rewardType
          if (element.type === parm.type && element.conditionAmount == parm.conditionAmount && element.conditionCount == parm.conditionCount && element.enable !== 'NO') {
            this.$alert('不能重复添加同等规则的活动', '提示')
            add = false
            return
          }
        });
      } else {
        this.selCouponData.forEach(element => {
          if (element.cardid === parm.cardid && element.enable !== 'NO') {
            this.$alert('不能重复添加同一张卡券', '提示')
            add = false
            return
          }
        });
      }
      if (add) { this.selCouponData.push(parm) }
    },
    next () {
      this.submit('next')
    },
    success () {
      if (this.selCouponData.length === 0) {
        this.$alert('请选择卡券', '提示')
        return
      }
      this.submit('success')
    },
    prev () {
      this.$emit('changePageShow', this.prevTap, 'prev')
    },
    save () {
      this.submit('save')
    },
    submit (type) {
      let arr = []
      this.selCouponData.forEach(element => {
        if (element.newAdd) {
          let obj = {
            activityId: JSON.parse(sessionStorage.getItem('activityId')),
            cardId: element.cardid,
            cardNum: element.cardNum,
            conditionAmount: element.conditionAmount,
            conditionCount: element.conditionCount,
            limitNum: element.limitNum,
            type: element.type
          }
          arr.push(obj)
        }
      });
      let parm = {
        activityId: JSON.parse(sessionStorage.getItem('activityId')),
        couponRewardConditions: arr
      }
      this.$http.put('/api-active/v1/api/activityCenter/activity/coupon', parm)
          .then((response) => {
            let data = response.body;
            if (data.resultCode === '200') {
              if (type === 'next') {
                this.$emit('changePageShow', this.nextTap)
              } else if (type === 'success') {
                this.$router.push({name: 'activityList'})
              } else if (type === 'save') {
                this.getActivityDetail()
                this.$alert('保存成功', '提示')
              }
              postLog('ACTIVITY_LIST_EDIT', parm.activityId, '', parm);
            } else {
              this.$alert(data.msg, '提示')
            }
          }, (request) => {
            this.$alert('请求出错', '提示')
          })
    },
    closeDialog () {
      this.show = false
    },
    get (parm) {
      console.log(parm)
    }
  }
}
</script>
<style lang="less" scoped>
  #actCoupon{
    .addBtn{
      margin-left:20px;
      .el-button{
        margin-left:20px;
      }
    }
    .couponTable{
      margin-top:20px;
    }
  }
</style>
